public class listdemo1 {
    static class ListNode{
        public int val;
        public ListNode next;
        public ListNode(int val){
            this.val = val;
        }
    }

    public ListNode head;

    public ListNode reverseList(){
//        没有节点
        if (head == null){
            return head;
        }
//        只有一个节点
        if (head.next == null){
            return head;
        }
        ListNode cur = head;

        head.next = null;
//        开始头插
        while (cur != null){
            ListNode curNext = cur.next;
            cur.next = head;
            head = cur;
            cur = curNext;
        }
        return head;
    }

//    寻找中间节点，进行删除
    public ListNode findCenter(){
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

//    输出该链表中倒数第k个节点
    public ListNode firdKey(int k){
        ListNode fast = head;
        ListNode slow = head;
        int count = 0;
        if (head == null){
            return head;
        }
//        判断k是否合法,不用size，怕size太大
//        if (k < 0 || k > size()){
//            return null;
//        }
        while(count != k-1){
            if (fast.next != null){
                fast = fast.next;
                count ++;
            }else {
                return null;
            }

        }

        while(count != k - 1){
            fast = fast.next;
            count ++;
        }
        while(fast.next != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }

    public ListNode partition(int x) {
        if (head ==null){
            return null;
        }

        ListNode cur = head;

        ListNode bs = null;
        ListNode be = null;
        ListNode as = null;
        ListNode ae = null;

        while(cur != null){
            if (cur.val < x){
                if (bs == null){
                    bs = cur;
                    be = cur;
                }else {
                    be.next = cur;
                    be = be.next;
                }
            }else {
                if (as == null){
                    as = cur;
                    ae = cur;
                }else {
                    ae.next = cur;
                    ae = ae.next;
                }
            }
            cur = cur.next;
        }
//        预防第一段为空
        if (bs == null){
            return as;
        }
//        预防，最后一个不是null，后台无法确定什么时候结束
        be.next = as;
        if (as != null){
//            手动置空
            ae.next = null;
        }
        return  bs;

    }
}
